#!/usr/bin/env bash

MY_DIR="$( cd "$( dirname $0)" && pwd )"
. "$MY_DIR/config.sh"
. "$MY_DIR/log.sh"

ONCE=0

while [[ $# -gt 0 ]]
do
    key="$1"
    case $key in
        --once)
            ONCE=1
        ;;
        *)
            echo "unknown option $key"
            exit -1
        ;;
    esac
    shift # past argument or value
done

log_init "merge_scanner.log"

while true; do
    # search for merge.this.directory file
    MERGE_DIR_FILES=$(find "$MERGE_IN_DIR" -name "merge.this.directory")
    log_this "  found $( echo "$ENDC_FILES" | grep -v ^$ | wc -l ) directories to merge"
    for MERGE_DIR_FILE in ${MERGE_DIR_FILES}; do
        rm -f "${MERGE_DIR_FILE}"
        MERGE_DIR=$( dirname "${MERGE_DIR_FILE}" )
        # remove intermediate file if any
        MERGE_INTERMEDIATE_FILES=$(find "$MERGE_DIR" -name "*.normalized.mp4")
        for MERGE_INTERMEDIATE_FILE in ${MERGE_INTERMEDIATE_FILES}; do
            rm -f "$MERGE_INTERMEDIATE_FILE"
        done
        MERGE_DIR_RELATIVE_PATH=$( realpath --relative-to "$MERGE_IN_DIR" "$MERGE_DIR" )
        MEDIA_FILES=$( find "$MERGE_DIR" -name "*.webm" -or -name "*.mkv")
        log_this "    dir ${MERGE_DIR} contains $( echo "${MEDIA_FILES}" | grep -v ^$ | wc -l ) media files"

        MERGE_CMD=("$MERGE" "-v" "warning")
        for MEDIA_FILE in ${MEDIA_FILES}; do
            log_this "      input: $MEDIA_FILE"
            MEDIA_FILE_RELATIVE_PATH=$( realpath --relative-to ${MERGE_IN_DIR} ${MEDIA_FILE} )
            MERGE_CMD+=("-i" "$MEDIA_FILE")
        done
        # use the name of parent dir of "merge.this.directory" as output file name
        MERGE_OUTPUT_FILE="${MERGE_DIR}.mp4"
        log_this "      output: $MERGE_OUTPUT_FILE"
        MERGE_CMD+=("-c:v" "libx264" "-preset" "ultrafast" "-c:a" "aac" "$MERGE_OUTPUT_FILE")
        log_this "      ${MERGE_CMD[@]}"
        ${MERGE_CMD[@]} 1>>"$LOG_DIR/$LOG_NAME" 2>&1
        MERGE_ERROR=$?
        if [[ $MERGE_ERROR -ne 0 ]]; then
            for MEDIA_FILE in ${MEDIA_FILES}; do
                MEDIA_FILE_RELATIVE_PATH=$( realpath --relative-to ${MERGE_IN_DIR} $( dirname ${MEDIA_FILE} ) )
                MERGE_FAILURE_DIR="$HISTORY_DIR/merge-failure/$MEDIA_FILE_RELATIVE_PATH/"
                mkdir -p "$MERGE_FAILURE_DIR"
                mv -f "${MEDIA_FILE}" "$MERGE_FAILURE_DIR"
                mv -f "${MEDIA_FILE%.*}.ts" "$MERGE_FAILURE_DIR"
                mv -f "${MEDIA_FILE%.*}.ctx" "$MERGE_FAILURE_DIR"
            done
            # backup endc.info if any
            mkdir -p "$HISTORY_DIR/merge-failure/$MERGE_DIR_RELATIVE_PATH/"
            cp -f "$MERGE_DIR/endc.info" "$HISTORY_DIR/merge-failure/$MERGE_DIR_RELATIVE_PATH/"

            # remove output if any
            rm -f "${MERGE_OUTPUT_FILE}"
            log_this "    merge failed, error $MERGE_ERROR, media files moved to $HISTORY_DIR/merge-failure/"
        else
            # backup media,ts,ctx files
            for MEDIA_FILE in ${MEDIA_FILES}; do
                MEDIA_FILE_RELATIVE_PATH=$( realpath --relative-to ${MERGE_IN_DIR} $( dirname ${MEDIA_FILE} ) )
                MERGE_SUCCESS_DIR="$HISTORY_DIR/merge-success/$MEDIA_FILE_RELATIVE_PATH/"
                mkdir -p "$MERGE_SUCCESS_DIR"
                mv -f "${MEDIA_FILE}" "$MERGE_SUCCESS_DIR"
                mv -f "${MEDIA_FILE%.*}.ts" "$MERGE_SUCCESS_DIR"
                mv -f "${MEDIA_FILE%.*}.ctx" "$MERGE_SUCCESS_DIR"
            done
            # backup endc.info file if any
            mkdir -p "$HISTORY_DIR/merge-success/$MERGE_DIR_RELATIVE_PATH/"
            cp -f "$MERGE_DIR/endc.info" "$HISTORY_DIR/merge-success/$MERGE_DIR_RELATIVE_PATH/"
            # send endc.info and merged file to merge-out
            mkdir -p "$MERGE_OUT_DIR/$MERGE_DIR_RELATIVE_PATH"
            mv -f "${MERGE_OUTPUT_FILE}" "$MERGE_OUT_DIR/$MERGE_DIR_RELATIVE_PATH"
            mv -f "$MERGE_DIR/endc.info" "$MERGE_OUT_DIR/$MERGE_DIR_RELATIVE_PATH"
            log_this "    merge success, media files copied to $HISTORY_DIR/merge-success/, merged file moved to $MERGE_OUT_DIR/$MERGE_DIR_RELATIVE_PATH"
        fi

        if [[ "${MERGE_DIR}" != "${MERGE_IN_DIR}" ]]; then
            rm -rf "${MERGE_DIR}"
        fi
    done

    OLD_MERGE_IN_FILES=$(find "$MERGE_IN_DIR" -depth -type f -mtime +1)
    for OLD_MERGE_IN_FILE in ${OLD_MERGE_IN_FILES}; do
        log_this "  $OLD_MERGE_IN_FILE not used in one day, removed"
        rm -f "$OLD_MERGE_IN_FILE"
    done
    EMPTY_MERGE_IN_SUB_DIRS=$( find "$MERGE_IN_DIR" -depth -type d -mtime +1 -empty -not -path "$MERGE_IN_DIR" )
    for EMPTY_MERGE_IN_SUB_DIR in ${EMPTY_MERGE_IN_SUB_DIRS}; do
        log_this "  $EMPTY_MERGE_IN_SUB_DIR not used in one day, removed"
        rm -rf "$EMPTY_MERGE_IN_SUB_DIR"
    done

    OLD_MERGE_OUT_FILES=$(find "$MERGE_OUT_DIR" -depth -type f -mtime +7)
    for OLD_MERGE_OUT_FILE in ${OLD_MERGE_OUT_FILES}; do
        log_this "  $OLD_MERGE_OUT_FILE kept over 7 days, removed"
        rm -f "$OLD_MERGE_OUT_FILE"
    done

    EMPTY_MERGE_OUT_SUB_DIRS=$( find "$MERGE_OUT_DIR" -depth -type d -mtime +1 -empty -not -path "$MERGE_OUT_DIR" )
    for EMPTY_MERGE_OUT_SUB_DIR in ${EMPTY_MERGE_OUT_SUB_DIRS}; do
        log_this "  $EMPTY_MERGE_OUT_SUB_DIR not used in one day, removed"
        rm -rf "$EMPTY_MERGE_OUT_SUB_DIR"
    done

    MERGE_MIDDLE_FILES=$(find "$TEMP_DIR" -depth -type f -mtime +1)
    for MERGE_MIDDLE_FILE in ${MERGE_MIDDLE_FILES}; do
        log_this "  $MERGE_MIDDLE_FILE not used in one day, removed"
        rm -rf "$MERGE_MIDDLE_FILE"
    done

    if [[ ${ONCE} -eq 1 ]]; then
        break
    fi

    sleep 1
    log_rotate_by_size
done
